package com.whc.common;

import com.whc.vo.TokenVO;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author wang-hai-cheng
 * @since 2021/12/11 21:49
 */
@WebFilter(urlPatterns = "/*")
@Component
public class LoginFilter implements Filter {
    private static final List<String> ignorePath = Arrays.asList("/login");
    public static final String onPath = "/on";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        if (!Cache.sw && !onPath.equals(requestURI)) {
            write(servletResponse, Constant.Message.OFF);
            return;
        }
        long start = System.currentTimeMillis();
        if (ignorePath.contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("====执行耗时:" + (System.currentTimeMillis() - start) + "ms");
            return;
        }
        String token = servletRequest.getParameter("token");
        if (token == null) {
            write(servletResponse, Constant.Message.ILLEGALITY_REQUEST);
            return;
        }
        TokenVO tokenVO = Cache.tokens.get(token);
        if (tokenVO == null) {
            write(servletResponse, Constant.Message.ILLEGALITY_REQUEST);
            return;
        }
        if (tokenVO.getCreatTime().isBefore(LocalDateTime.now().plusHours(-1L))) {
            write(servletResponse, Constant.Message.LOGIN_EXPIRE);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("====执行耗时:" + (System.currentTimeMillis() - start) + "ms");
    }

    private void write(ServletResponse response, String message) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
    }
}